package com.stylefeng.guns.rest.modular.wz.service.impl;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.persistence.dao.WzCouponMapper;
import com.stylefeng.guns.rest.common.persistence.dao.WzMapMergeMapper;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.persistence.dao.WzUserMergeMapper;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnWzCoupon;
import com.stylefeng.guns.rest.enums.EnWzMapMerge;
import com.stylefeng.guns.rest.enums.EnWzUserFinanceRecord;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.WzFinanceService;
import com.stylefeng.guns.rest.modular.wz.service.IWzUserMergeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import com.stylefeng.guns.rest.pay.method.PayMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 用户拼单表 服务实现类
 * </p>
 *
 * @author ruiyifeng123
 * @since 2019-03-04
 */
@Service
public class WzUserMergeServiceImpl extends ServiceImpl<WzUserMergeMapper, WzUserMerge> implements IWzUserMergeService {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzMapMergeMapper mapMergeMapper;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private WzFinanceService financeService;
    @Autowired
    private WzUserMergeMapper userMergeMapper;

    //用户发起拼单
    public Res createMerge(ParamMap paramMap) throws Exception{
        Long userCode = jwtTokenUtil.getUserCodeFromToken();//下单用户编号
        Long mapMergeId = paramMap.getLongMisValid("mapMergeId");
        int quantity = paramMap.getIntMisValid("quantity");//购买数量
        int amount = paramMap.getIntMisValid("amount");//前台计算价格
        int isRewardBalanceDeduction = paramMap.getIntMisValid("isRewardBalanceDeduction");//是否用积分余额抵扣：0-否;1-是
        int payMethod = paramMap.getIntMisValid("payMethod");//支付类型：1-支付宝;2-微信;
        WzUser user = cacheService.user(userCode);//用户信息
        WzMapMerge mapMerge = mapMergeMapper.selectById(mapMergeId);//拼单活动

        //后台金额计算
        int realAmount = quantity * mapMerge.getMergePrice();
        //现金支付
        if(isRewardBalanceDeduction == 0){
            if(amount != realAmount){
                return Res.fail("金额错误!");
            }
            Res res = createMergeCash(paramMap,user,mapMerge,payMethod,quantity,realAmount);
            return res;
        }
        return Res.fail();
    }

    /**
     * 加入拼单
     */
    public Res joinMerge(ParamMap paramMap) throws Exception {
        Long userCode = jwtTokenUtil.getUserCodeFromToken();//下单用户编号
        Long mapMergeId = paramMap.getLongMisValid("mapMergeId");
        int quantity = paramMap.getIntMisValid("quantity");//购买数量
        int amount = paramMap.getIntMisValid("amount");//前台计算价格
        int isRewardBalanceDeduction = paramMap.getIntMisValid("isRewardBalanceDeduction");//是否用积分余额抵扣：0-否;1-是
        int payMethod = paramMap.getIntMisValid("payMethod");//支付类型：1-支付宝;2-微信;
        Long userMergeId = paramMap.getLongMisValid("userMergeId");//用户拼单id
        WzUser user = cacheService.user(userCode);//用户信息
        WzMapMerge mapMerge = mapMergeMapper.selectById(mapMergeId);//拼单活动
        WzUserFinanceRecord userRewardFinanceRecord = null;//用户拼单订单积分抵扣记录
        WzUserFinanceRecord userFinanceRecord = null;//用户拼单支付记录
        WzUserMerge userMerge = userMergeMapper.selectById(userMergeId);//用户发起的拼单

        //拼单人判断
        if (userMerge.getUserCode().toString().equals(user.getUserCode().toString())) {
            return Res.fail("不可以参与自己发起的拼单!");
        }
        //订单原金额计算
        int realAmount = quantity * mapMerge.getMergePrice();

        //现金支付
        if (isRewardBalanceDeduction == 0) {
            if (amount != realAmount) {
                return Res.fail("金额错误!");
            }
            Res res = joinMergeCash(paramMap,user, mapMerge, payMethod, quantity, realAmount,userMerge);
            return res;
        }

        //积分余额抵扣
//        if (isRewardBalanceDeduction == 1) {
//            if (user.getRewardBalance() <= 0) {
//                return Res.fail("积分余额不足!");
//            }
//            Res res = joinMergeReward(paramMap,user, mapMerge, payMethod, amount, quantity, realAmount,userMerge);
//            return res;
//        }
        return Res.fail();
    }

    //积分余额抵扣-参与
//    private Res joinMergeReward(ParamMap paramMap, WzUser user, WzMapMerge mapMerge, int payMethod, int amount, int quantity, int realAmount, WzUserMerge userMerge) throws Exception{
//        WzUserFinanceRecord userFinanceRecord = null;//用户拼单支付记录
//        WzUserFinanceRecord userRewardFinanceRecord = new WzUserFinanceRecord();;//用户拼单订单积分抵扣记录
//        WzUserMergeDetail userMergeDetail = new WzUserMergeDetail();//拼单详情
//        userMergeDetail.setAmount(realAmount);
//        if(user.getRewardBalance() >= realAmount){//积分>=总价
//            user.setRewardBalance(user.getRewardBalance()  - realAmount);//用户积分余额处理
//            userRewardFinanceRecord.setAmount(realAmount);//资金记录
//            userMergeDetail.setRewardAmount(userRewardFinanceRecord.getAmount());
//            realAmount = 0;
//        }else{//积分<总价
//            userRewardFinanceRecord.setAmount(user.getRewardBalance());//积分资金记录
//            realAmount = realAmount - user.getRewardBalance();
//            user.setRewardBalance(0);//用户积分余额处理
//            userFinanceRecord = new WzUserFinanceRecord();//支付资金记录
//            userFinanceRecord.setId(IdWorker.getId());
//            userFinanceRecord.setAmount(realAmount);
//            userMergeDetail.setCashAmount(userFinanceRecord.getAmount());
//        }
//        //实际金额处理
//        if(amount != realAmount){
//            return Res.fail("金额错误!");
//        }
//        paramMap.put("userMergeId",userMerge.getUserMergeId());
//        //数据保存处理
//        boolean r = financeService.joinMergeReward(realAmount,quantity,mapMerge,user,userFinanceRecord,userRewardFinanceRecord,userMerge,userMergeDetail);
//        if(r){
//            if(realAmount > 0){
//                //返回支付数据
//                if(payMethod == EnWzUserFinanceRecord.payMethod_alipay.getIndex()){//支付宝支付
//                    String str = PayMethod.aliAppPay(userFinanceRecord.getId().toString(),realAmount,"外赚-拼单订单");
//                    paramMap.put("alipay",str);
//                    return Res.success(paramMap);
//                }else if(payMethod == EnWzUserFinanceRecord.payMethod_weixin.getIndex()){//微信支付
//                    Map m = PayMethod.wxAppPay(realAmount,userFinanceRecord.getId().toString(),"外赚-拼单订单","8.8.8.8");
//                    paramMap.put("weixin",m);
//                    return Res.success(paramMap);
//                }
//            }
//            return Res.success(paramMap);
//        }
//        return Res.fail();
//    }

    //积分余额抵扣-发起
//    private Res createMergeReward(ParamMap paramMap,WzUser user, WzMapMerge mapMerge, int payMethod, int amount, int quantity,int realAmount) throws  Exception{
//        WzUserFinanceRecord userFinanceRecord = null;//用户拼单支付记录
//        WzUserFinanceRecord userRewardFinanceRecord = new WzUserFinanceRecord();;//用户拼单订单积分抵扣记录
//        //用户拼单详情
//        WzUserMergeDetail userMergeDetail = new WzUserMergeDetail();
//        userMergeDetail.setAmount(realAmount);
//        userRewardFinanceRecord.setId(IdWorker.getId());
//
//        if(user.getRewardBalance() >= realAmount){//积分>=总价
//            user.setRewardBalance(user.getRewardBalance()  - realAmount);//用户积分余额处理
//            userRewardFinanceRecord.setAmount(realAmount);//资金记录
//            realAmount = 0;
//        }else{//积分<总价
//            userRewardFinanceRecord.setAmount(user.getRewardBalance());//积分资金记录
//            realAmount = realAmount - user.getRewardBalance();
//            user.setRewardBalance(0);//用户积分余额处理
//            userFinanceRecord = new WzUserFinanceRecord();//支付资金记录
//            userFinanceRecord.setId(IdWorker.getId());
//            userFinanceRecord.setAmount(realAmount);
//        }
//
//        //实际金额处理
//        if(amount != realAmount){
//            return Res.fail("金额错误!");
//        }
//        WzUserMerge userMerge = new WzUserMerge();
//        userMerge.setUserMergeId(IdWorker.getId());
//        paramMap.put("userMergeId",userMerge.getUserMergeId());
//        //数据保存处理
//        boolean r = financeService.createMergeCashReward(realAmount,quantity,mapMerge,user,userFinanceRecord,userRewardFinanceRecord,userMerge,userMergeDetail);
//        if(r){
//            if(realAmount > 0){
//                //返回支付数据
//                if(payMethod == EnWzUserFinanceRecord.payMethod_alipay.getIndex()){//支付宝支付
//                    String str = PayMethod.aliAppPay(userFinanceRecord.getId().toString(),realAmount,"外赚-拼单订单");
//                    paramMap.put("alipay",str);
//                    return Res.success(paramMap);
//                }else if(payMethod == EnWzUserFinanceRecord.payMethod_weixin.getIndex()){//微信支付
//                    Map m = PayMethod.wxAppPay(realAmount,userFinanceRecord.getId().toString(),"外赚-拼单订单","8.8.8.8");
//                    paramMap.put("weixin",m);
//                    return Res.success(paramMap);
//                }
//            }
//            return Res.success(paramMap);
//        }
//        return Res.fail();
//    }

    //现金支付-发起
    private Res createMergeCash(ParamMap paramMap,WzUser user, WzMapMerge mapMerge, int payMethod, int quantity,int realAmount) throws Exception{
        WzUserFinanceRecord userFinanceRecord = new WzUserFinanceRecord();//现金支付记录
        userFinanceRecord.setId(IdWorker.getId());
        userFinanceRecord.setPayMethod(payMethod);

        WzUserMerge userMerge = new WzUserMerge();
        userMerge.setUserMergeId(IdWorker.getId());

        WzUserMergeDetail userMergeDetail = new WzUserMergeDetail();
        userMergeDetail.setUserMergeDetailId(IdWorker.getId());

        WzCoupon coupon = cacheService.coupon(mapMerge.getCouponId());//券信息
        if(coupon.getUseType() == EnWzCoupon.UserType_Delivery.getIndex()){
            String userInfoId = paramMap.getStrMisValid("userInfoId");
            userMergeDetail.setUserInfoId(userInfoId);
        }

        paramMap.put("userMergeDetailId",userMergeDetail.getUserMergeDetailId());
        //数据保存处理
        boolean r = financeService.createMergeCash(userMergeDetail,realAmount,quantity,mapMerge,user,userFinanceRecord,userMerge);
        if(r){
            //返回支付数据
            if(payMethod == EnWzUserFinanceRecord.payMethod_alipay.getIndex()){//支付宝支付
                String str = PayMethod.aliAppPay(userFinanceRecord.getId().toString(),realAmount,"外赚-拼单订单");
                paramMap.put("alipay",str);
                return Res.success(paramMap);
            }else if(payMethod == EnWzUserFinanceRecord.payMethod_weixin.getIndex()){//微信支付
                Map m = PayMethod.wxAppPay(realAmount,userFinanceRecord.getId().toString(),"外赚-拼单订单","8.8.8.8");
                paramMap.put("weixin",m);
                return Res.success(paramMap);
            }
        }
        return Res.fail();
    }


    //现金支付-参与
    private Res joinMergeCash(ParamMap paramMap,WzUser user, WzMapMerge mapMerge, int payMethod, int quantity,int realAmount,WzUserMerge userMerge) throws Exception{
        WzUserFinanceRecord userFinanceRecord = new WzUserFinanceRecord();//现金支付记录
        userFinanceRecord.setId(IdWorker.getId());
        userFinanceRecord.setPayMethod(payMethod);

        WzUserMergeDetail userMergeDetail = new WzUserMergeDetail();
        userMergeDetail.setUserMergeDetailId(IdWorker.getId());

        WzCoupon coupon = cacheService.coupon(mapMerge.getCouponId());//券信息
        if(coupon.getUseType() == EnWzCoupon.UserType_Delivery.getIndex()){
            String userInfoId = paramMap.getStrMisValid("userInfoId");
            userMergeDetail.setUserInfoId(userInfoId);
        }
        paramMap.put("userMergeDetailId",userMergeDetail.getUserMergeDetailId());

        //数据保存处理
        boolean r = financeService.joinMergeCash(userMergeDetail,realAmount,quantity,mapMerge,user,userFinanceRecord,userMerge);
        if(r){
            //返回支付数据
            if(payMethod == EnWzUserFinanceRecord.payMethod_alipay.getIndex()){//支付宝支付
                String str = PayMethod.aliAppPay(userFinanceRecord.getId().toString(),realAmount,"外赚-拼单订单");
                paramMap.put("alipay",str);
                return Res.success(paramMap);
            }else if(payMethod == EnWzUserFinanceRecord.payMethod_weixin.getIndex()){//微信支付
                Map m = PayMethod.wxAppPay(realAmount,userFinanceRecord.getId().toString(),"外赚-拼单订单","8.8.8.8");
                paramMap.put("weixin",m);
                return Res.success(paramMap);
            }
        }
        return Res.fail();
    }
}
